import jwt
import time
from settings.config import *
from flask import current_app


# class JwtTool:
#     def __init__(self)->None:
#         self.secret = 'lkjhgfdddhjncfghjkmv'
#
#     # 加密
#     def jwt_encode(self,payload):
#         return jwt.encode(payload,self.secret,algorithm='HS256')
#
#     # 解密
#     def jwt_decode(self,token):
#         return jwt.decode(token,self.secret,algorithms='HS256')
#
#
#     # 对比
#     def check_token(self,token):
#         print("check_token")
#         payload = jwt.decode(token,self.secret,algorithms='HS256')
#         newtoken = jwt.decode(payload,self.secret,algorithms='HS256')
#         if token == newtoken:
#             # 验证过期时间
#             nowtime = int(time.time())
#             if nowtime - payload['data']['exp']>36000:
#                 return False
#             return True
#         return False
# myjwt = JwtTool()


class JwtTool():

    '''
    jwt管理
    '''
    def jwt_encode(self, payload, ex=3600*24):
        '''
        :param payload:  载荷
        :return:   string jwt
        '''

        payload["exp"] = int(time.time()) + ex
        secret_key = current_app.config.get("SECRET_KEY")
        token = jwt.encode(payload, secret_key, algorithm="HS256")
        return token

    def jwt_decode(self, token):
        """
        :param token:
        :return:
        """
        secret_key = current_app.config.get("SECRET_KEY")
        try:
            payload = jwt.decode(token, secret_key, algorithms="HS256")
        except Exception as e:
            print(e)
            return False
        return payload

    def valid(self, token):
        """
        校验JWT
        :param token: JWT
        :return: Dict payload
        """
        secret_key = current_app.config.get("SECRET_KEY")
        try:
            payload = jwt.decode(token, secret_key, algorithms="HS256")
            ntime = int(time.time())
            if payload["exp"] < ntime:
                return False
            return True
        except Exception as e:
            print(e)
            return False

    def check_token(self, token):
        secret_key = current_app.config.get("SECRET_KEY")
        payload = jwt.decode(token, secret_key, algorithms="HS256")
        new_token = jwt.encode(payload, secret_key, algorithm="HS256")
        if token == new_token:
            return True
        return False


myjwt = JwtTool()

# 1668680261
# 1668766586

# 1668680289
# 1668766586
